<template>
  <div class="assignment-header">
    <button class="back-button" @click="$router.go(-1)"><img src="@/assets/svgs/left.svg" alt="Back" /></button>
    <span class="correct_header1">{{ submit_time }}</span>
    <span class="correct_header4" v-if="selectedHomework">{{ selectedHomework.homeworkName }}:</span>
    <span class="correct_header2">{{ user_name }}</span>
    <span class="correct_header3" v-if="selectedHomework">截止提交时间：{{ selectedHomework.homeworkDeadline }}</span>
    <button type="success" class="assign_button" @click="assignHome">提交批改</button>
  </div>
  <div class="assignment-grading">
    <el-collapse v-model="activeNames">
      <el-collapse-item v-for="(item, index) in assignment" :key="item.studentAnswerId" :name="index">
        <template #title>
          <h2 class="aler2">&nbsp;&nbsp;&nbsp;题目 {{ index + 1 }}&nbsp;&nbsp;&nbsp; ({{ item.scoreSet }}分)</h2>
        </template>
        <div></div>
        <p class="correct_question">{{ item.question }}</p>
        <div class="answer_content">
          <p class="smalltitle">学生答案:</p>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ item.answer }}
        </div>
        <div class="correct_content2">
          <p class="correct_title2">参考答案</p>
          <p class="correct_answer_cotent">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{{ item.standardAnswer }}</p>
        </div>
        <div class="correct_content3">
          <span><span style="color: brown;font-weight: 900;">*&nbsp;</span>您的给分：</span>
          <el-input-number v-model="item.score" :min="0" :max="100" controls-position="right" size="large"
            @change="handleChange" />
          <p>您的评语：</p>
          <el-input class="grade_input" v-model="item.comment" placeholder="请输入评语" />
        </div>
      </el-collapse-item>
    </el-collapse>
  </div>
</template>



<script setup>
import { ref } from 'vue';
import { ElMessage, ElLoading } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import { useCounterStore } from "@/stores/counter";
import { gethomeworkService, getHomeworkByIdService, getStuAnswerService, updateHomeworkService } from '@/api/homework';

//获取上一个页面给的作业和学生id
const router = useRouter();
const route = useRoute();
const homeworkId = ref(route.query.homeworkId);
const userId = ref(route.query.userId);
console.log("获取的作业id:", homeworkId.value);
console.log("获取的学生id:", userId.value);

//从pinia获取课程ID
let store = useCounterStore();
const courseManageId = store.courseManageId;
console.log("获取的课程id:", courseManageId);


//导航栏部分查询作业列表里面的作业名称和作业截止时间
const selectedHomework = ref(null);
const fetchHomeworkList = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  try {
    const response = await gethomeworkService(courseManageId);
    if (!response || !response.data) {
      throw new Error('API返回数据格式错误');
    }
    const homeworkData = Array.isArray(response.data) ? response.data : [];
    // 遍历作业数据数组，找到与当前作业ID匹配的作业
    const matchingHomework = homeworkData.find(item => item.homeworkId === Number(homeworkId.value));
    if (matchingHomework) {
      selectedHomework.value = {
        homeworkId: matchingHomework.homeworkId,
        homeworkName: matchingHomework.homeworkName,
        homeworkDeadline: matchingHomework.deadline,
      };
      console.log('获取的作业:', selectedHomework);
    } else {
      console.warn('未找到匹配的作业');
      selectedHomework.value = null; // 如果没有找到匹配的作业，清空 selectedHomework
    }
  } catch (error) {
    console.error('获取作业列表错误:', error);
  } finally {
    loading.close();
  }
};
fetchHomeworkList();


//导航栏部分获取学生姓名和提交时间
const user_name = ref('');
const submit_time = ref('');
const resulthomework = async () => {
  try {
    const response = await getHomeworkByIdService(homeworkId.value);
    console.log("获取的作业:", response);
    if (response && response.data) {
      const students = response.data.map(item => ({
        userId: item.userId,
        userName: item.userName,
        submitTime: item.submitTime
      }));

      console.log("后端返回的学生数据:", students);

      const currentStudent = students.find(student => student.userId === Number(userId.value));
      if (currentStudent) {
        user_name.value = currentStudent.userName;
        submit_time.value = currentStudent.submitTime;
      } else {
        console.warn('未找到匹配的学生信息');
        user_name.value = '未知学生';
        submit_time.value = '未知时间';
      }
      console.log("获取的学生信息:", user_name.value, submit_time.value);
      console.log("获取的学生信息:", currentStudent)
      return students;
    } else {
      ElMessage.error("未获取到作业数据");
      return [];
    }
  } catch (err) {
    ElMessage.error(`获取作业内容失败，请稍后再试: ${err.message}`);
    console.error('Error:', err);
    return [];
  }
};
const students = ref([]);
resulthomework().then(data => {
  students.value = data;
});


//批改作业部分获取信息
const assignment = ref([]); // 存储作业详情数据
const details = ref(false);
const viewHomework = async (userId) => {
  console.log("请求的 userId:", userId, "homeworkId:", homeworkId.value);

  if (isNaN(Number(userId)) || isNaN(Number(homeworkId.value))) {
    ElMessage.error("Invalid userId or homeworkId");
    return;
  }

  try {
    const response = await getStuAnswerService(homeworkId.value, userId);
    console.log("获取的作业详情:", response);
    if (response && response.data) {
      assignment.value = response.data; // 存储后端返回的所有数据
      details.value = true; // 显示作业详情模块
    } else {
      ElMessage.error("未获取到作业详情数据");
    }
  } catch (err) {
    ElMessage.error(`获取作业详情失败: ${err.message}`);
  }
};
viewHomework(userId.value);

const activeNames = ref(); // 默认不展开个面板
//提交批改
const assignHome = async () => {
  try {
   

    const loading = ElLoading.service({
      lock: true,
      text: '提交中...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    await updateHomeworkService(data);
    ElMessage.success('批改成功');
    router.go(-1);
  } catch (error) {
    ElMessage.error(`提交批改失败: ${error.message}`);
  } 
};

</script>

<style scoped>
.assignment-header {
  display: flex;
  height: 7lvh;
  width: 99lvw;
  background-color: #13227A;
  color: white;
}

.back-button {
  background-color: transparent;
  border: none;
  color: white;
  cursor: pointer;
  font-size: 18px;
  font-weight: 700;
}

.back-button:hover {
  color: #d72d2d;
}

.correct_header1 {
  margin-left: 1%;
  margin-top: 1.2%;
}

.correct_header2 {
  margin-left: 1%;
  margin-top: 1.2%;
}

.correct_header3 {
  margin-left: 13%;
  margin-top: 1.2%;
}

.correct_header4 {
  margin-left: 10%;
  margin-top: 1.2%;
}

.assign_button {
  position: absolute;
  margin-top: 0.8%;
  margin-left: 88%;
  height: 5%;
  width: 10%;
  background-color: #1a3a8b;
  color: white;
  border: 1px solid #ffffff;
  cursor: pointer;
  border-radius: 5px;
}

.assign_button:hover {
  background-color: #98a2bb;
}

.assignment-grading {
  height: 89lvh;
  max-height: 89lvh;
  overflow-y: auto;
}

.correct_content {
  display: flex;
  flex-direction: column;
  height: 89lvh;
  width: 99lvw;
}

.correct_content1 {
  float: left;
  height: 30%;
  width: 100%;
  background-color: rgb(255, 255, 255);
}

.correct_title {
  margin-left: 4%;
  font-size: 22px;
  font-weight: 700;
  color: rgb(0, 0, 0);
}

.correct_question {
  margin-left: 2%;
  font-size: 18px;
  font-weight: 400;
  line-height: 10%;
  color: rgb(50, 47, 47);
}

.answer_content {
  margin-left: 2%;
  font-size: 14px;
  font-weight: 400;
  width: 95%;
  color: rgb(5, 5, 5);
  background-color: #f5f7f9;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.smalltitle {
  font-size: 16px;
  font-weight: 700;
  line-height: 5lvh;
  color: rgb(54, 54, 54);
}

.correct_content2 {
  float: left;
  height: 25%;
  margin-top: 1.5%;
  margin-left: 2%;
  width: 95%;
  background-color: #EFF6FF;
}

.correct_title2 {
  margin-left: 0.5%;
  font-size: 20px;
  font-weight: 700;
  line-height: 10%;
  color: rgb(0, 0, 0);
}

.correct_answer_cotent {
  font-size: 16px;
  color: #4B5563;
}

.correct_content3 {
  float: left;
  height: 24%;
  margin-top: 0.5%;
  margin-left: 2%;
  width: 94.5%;
  background-color: #EFF6FF;
  padding-top: 0.5%;
  padding-left: 0.5%;
}


.grade_input {
  margin-left: 0.3%;
  margin-bottom: 0.31%;
  width: 99%;
  height: 6lvh;
}


.aler2 {
  color: #333;
}

.aler3 {
  font-size: 16px;
  line-height: 1.6;
  margin-top: 10px;
  margin-bottom: 20px;
  color: #666;
  margin-left: 5%;
}

.correct_button {
  margin-left: 4%;
  margin-top: 1%;
  width: 92%;
  height: 10%;
}

.correct_button1 {
  margin-left: 25%;
  width: 12.5%;
  height: 80%;
  font-size: 24px;
  background-color: #13227A;
  color: white;
  border: 1px solid #ffffff;
  cursor: pointer;
  border-radius: 5px;
}

.correct_button1:hover {
  background-color: rgb(202, 124, 124);
}
</style>